import React, { useEffect, useState } from 'react';
import { Typography, Tag, Space, Button, message } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { SearchTable } from '../../components/common/Table/SearchTable';
import { BorrowModal } from '../../components/common/Modal/BorrowModal';
import { ConfirmModal } from '../../components/common/Modal/ConfirmModal';
import { useBorrow } from '../../hooks/useBorrow';
import type { BorrowRecord, CreateBorrowRequest, UpdateBorrowRequest } from '../../store/slices/borrowSlice';

const { Title } = Typography;

interface BorrowFormValues {
  userId: number;
  materialId: number;
  expectedReturn: string;
  purpose: string;
}

export const BorrowList: React.FC = () => {
  const {
    borrows,
    loading,
    createBorrow,
    modifyBorrow,
    removeBorrow,
    returnBorrow,
    refreshBorrows,
    initBorrows
  } = useBorrow();

  const [searchValue, setSearchValue] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingBorrow, setEditingBorrow] = useState<BorrowRecord | null>(null);
  const [modalLoading, setModalLoading] = useState(false);
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [deletingBorrow, setDeletingBorrow] = useState<{ id: number, materialName: string } | null>(null);
  const [deleteLoading, setDeleteLoading] = useState(false);

  // 初始化数据
  useEffect(() => {
  
    initBorrows();
  }, [initBorrows]);

  // 调试信息
  useEffect(() => {
  }, [borrows, loading]);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '借用人',
      dataIndex: 'userName',
      key: 'userName',
      width: 120,
    },
    {
      title: '物资名称',
      dataIndex: 'materialName',
      key: 'materialName',
      width: 150,
    },
    {
      title: '借用日期',
      dataIndex: 'borrowDate',
      key: 'borrowDate',
      width: 120,
    },
    {
      title: '预计归还',
      dataIndex: 'expectedReturn',
      key: 'expectedReturn',
      width: 120,
    },
    {
      title: '实际归还',
      dataIndex: 'actualReturn',
      key: 'actualReturn',
      width: 120,
      render: (actualReturn: string) => actualReturn || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status: string, record: BorrowRecord) => {
        const statusConfig = {
          borrowed: { color: 'blue', text: '借用中' },
          returned: { color: 'green', text: '已归还' },
          overdue: { color: 'red', text: '已逾期' },
        };
        const config = statusConfig[status as keyof typeof statusConfig];
        return (
          <Space>
            <Tag color={config.color}>{config.text}</Tag>
            {status !== 'returned' && (
              <Button
                type="link"
                size="small"
                onClick={() => handleReturn(record.id, record.materialName)}
              >
                归还
              </Button>
            )}
          </Space>
        );
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: BorrowRecord) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id, record.materialName)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 其他处理函数保持不变...
  const handleSearch = (value: string) => {
    setSearchValue(value);
  };

  const handleAdd = () => {
    setEditingBorrow(null);
    setIsModalVisible(true);
  };

  const handleEdit = (borrow: BorrowRecord) => {
    setEditingBorrow(borrow);
    setIsModalVisible(true);
  };

  const handleFormSubmit = async (values: BorrowFormValues) => {
    setModalLoading(true);
    try {
      if (editingBorrow) {
        const updateData: UpdateBorrowRequest = {
          id: editingBorrow.id,
          ...values
        };
        await modifyBorrow(updateData);
        message.success('借用记录更新成功');
      } else {
        const createData: CreateBorrowRequest = {
          ...values
        };
        await createBorrow(createData);
        message.success('借用记录添加成功');
      }
      setIsModalVisible(false);
    } catch (error) {
      message.error(editingBorrow ? '更新借用记录失败' : '添加借用记录失败');
      throw error;
    } finally {
      setModalLoading(false);
    }
  };

  const handleReturn = async (borrowId: number, materialName: string) => {
    try {
      await returnBorrow(borrowId);
      message.success(`"${materialName}" 归还成功`);
    } catch (error) {
      message.error('归还物资失败');
    }
  };

  const handleDelete = (borrowId: number, materialName: string) => {
    setDeletingBorrow({ id: borrowId, materialName });
    setConfirmModalVisible(true);
  };

  const handleDeleteConfirm = async () => {
    if (!deletingBorrow) return;
    setDeleteLoading(true);
    try {
      await removeBorrow(deletingBorrow.id);
      message.success('借用记录删除成功');
      setConfirmModalVisible(false);
      setDeletingBorrow(null);
    } catch (error) {
      message.error('删除借用记录失败');
    } finally {
      setDeleteLoading(false);
    }
  };

  const handleDeleteCancel = () => {
    setConfirmModalVisible(false);
    setDeletingBorrow(null);
  };

  const handleRefresh = () => {
    refreshBorrows();
    message.info('刷新借用记录');
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingBorrow(null);
  };

  const filteredData = borrows.filter(borrow =>
    borrow.userName?.toLowerCase().includes(searchValue.toLowerCase()) ||
    borrow.materialName?.toLowerCase().includes(searchValue.toLowerCase()) ||
    borrow.purpose?.toLowerCase().includes(searchValue.toLowerCase())
  );

  return (
    <div>
      <Title level={2}>借用记录</Title>
      {/* 
      <div style={{ marginBottom: 16 }}>
        <div>数据条数: {borrows.length}</div>
        <div>过滤后条数: {filteredData.length}</div>
        <div>加载状态: {loading ? '加载中...' : '完成'}</div>
      </div> */}

      <SearchTable<BorrowRecord>
        tableTitle="借用记录列表"
        columns={columns}
        dataSource={filteredData}
        rowKey="id"
        onSearch={handleSearch}
        onAdd={handleAdd}
        onRefresh={handleRefresh}
        searchPlaceholder="搜索借用人、物资名称、用途..."
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
        }}
        loading={loading}
      />

      <BorrowModal
        visible={isModalVisible}
        editingBorrow={editingBorrow}
        onSubmit={handleFormSubmit}
        onCancel={handleCancel}
        loading={modalLoading}
      />

      <ConfirmModal
        open={confirmModalVisible}
        title="确认删除"
        content={
          <div>
            <p>确定要删除借用记录 <strong>"{deletingBorrow?.materialName}"</strong> 吗？</p>
            <p style={{ color: '#ff4d4f' }}>此操作不可恢复，请谨慎操作！</p>
          </div>
        }
        onConfirm={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
        type="danger"
        confirmText="删除"
        cancelText="取消"
        loading={deleteLoading}
      />
    </div>
  );
};

export default BorrowList;